import bcrypt from 'bcryptjs';
import { getPool } from './src/database/db.js';
import { log } from './src/utils/logger.js';

async function createAdmin() {
  const pool = getPool();
  
  try {
    console.log('🔐 创建管理员账户...');
    
    const username = 'samygood';
    const password = 'samyxue8341';
    const email = 'admin@laoxue.com';
    
    // 加密密码
    const hashedPassword = await bcrypt.hash(password, 10);
    console.log('✅ 密码加密完成');
    
    // 检查用户是否已存在
    const [existing] = await pool.execute(
      'SELECT id FROM users WHERE username = ?',
      [username]
    );
    
    if (existing.length > 0) {
      console.log('⚠️  用户已存在，更新密码...');
      await pool.execute(
        'UPDATE users SET password = ?, email = ? WHERE username = ?',
        [hashedPassword, email, username]
      );
      console.log('✅ 管理员密码已更新');
    } else {
      console.log('➕ 创建新用户...');
      await pool.execute(
        'INSERT INTO users (username, password, email, totp_enabled) VALUES (?, ?, ?, ?)',
        [username, hashedPassword, email, 0]
      );
      console.log('✅ 管理员账户创建成功');
    }
    
    console.log('');
    console.log('📋 管理员账户信息：');
    console.log('   用户名:', username);
    console.log('   密码:', password);
    console.log('   邮箱:', email);
    console.log('');
    console.log('🎉 完成！现在可以使用此账户登录了。');
    
    process.exit(0);
  } catch (error) {
    console.error('❌ 创建管理员失败:', error.message);
    console.error(error);
    process.exit(1);
  }
}

// 执行
createAdmin();

